package cn.itcast.hello;


import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

/**
 * @author KTL
 * @version V1.0
 * @Package cn.itcast.hello
 * @date 2021/2/21 0021 10:31
 * @Copyright © 2015-04-29  One for each, and two for each
 *      演示：flink-datastream-api-实现wordcount
 *      注意：在flink1.12中流批如何区分？
 */
public class WordCount2 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env =StreamExecutionEnvironment.getExecutionEnvironment();
      //  env.setRuntimeMode(RuntimeExecutionMode.BATCH);
        DataStream<String> line = env.fromElements("itcast hadoop spark", "itcast hadoop spark", "itcast hadoop", "itcast");
        DataStream<String> words = line.flatMap(new FlatMapFunction<String, String>() {
            @Override
            public void flatMap(String value, Collector<String> out) throws Exception {
                final String[] arr = value.split(" ");
                for (String s : arr) {
                    out.collect(s);
                }
            }
        });
        DataStream<Tuple2<String, Integer>> wordAndOne = words.map(new MapFunction<String, Tuple2<String, Integer>>() {
            @Override
            public Tuple2<String, Integer> map(String value) throws Exception {
                return Tuple2.of(value, 1);
            }
        });
         KeyedStream<Tuple2<String, Integer>, String> grouped = wordAndOne.keyBy(t -> t.f0);
        SingleOutputStreamOperator<Tuple2<String, Integer>> result = grouped.sum(1);
         result.print();
         env.execute();
    }
}
